package com.css.fxfzaqbz.modules.callJcData.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.PageUtil;
import com.css.fxfzaqbz.base.response.RestResponse;
import com.css.fxfzaqbz.base.upload.entity.AttachmentInfoEntity;
import com.css.fxfzaqbz.base.upload.service.AttachmentInfoService;
import com.css.fxfzaqbz.constants.YNEnum;
import com.css.fxfzaqbz.modules.callJcData.constonts.RedisKeyConstants;
import com.css.fxfzaqbz.modules.callJcData.entity.Gasholder;
import com.css.fxfzaqbz.modules.callJcData.entity.PageResult;
import com.css.fxfzaqbz.modules.callJcData.entity.SysDataVersion;
import com.css.fxfzaqbz.modules.callJcData.param.SysDataVersionPageParam;
import com.css.fxfzaqbz.modules.callJcData.param.SysDataVersionSameTypeDataExistParam;
import com.css.fxfzaqbz.modules.callJcData.param.SysDataVersionSaveMetaDataInfoParam;
import com.css.fxfzaqbz.modules.callJcData.repository.impl.SysDataVersionRepository;
import com.css.fxfzaqbz.modules.callJcData.result.ParsingResult;
import com.css.fxfzaqbz.modules.callJcData.service.GasholderService;
import com.css.fxfzaqbz.modules.callJcData.vo.SysDataVersionGetByVersionCodeVo;
import com.css.fxfzaqbz.modules.callJcData.vo.SysDataVersionPageVo;
import com.css.fxfzaqbz.modules.data.entity.Site;
import com.css.fxfzaqbz.modules.callJcData.service.SiteService;
import com.css.fxfzaqbz.modules.supergraph.vo.VersionVO;
import com.css.fxfzaqbz.util.*;
import com.css.fxfzaqbz.web.PlatformSessionContext;
import com.css.fxfzaqbz.zcpt.sys.entity.SUser;
import com.css.fxfzaqbz.zcpt.sys.service.SUserService;
import com.css.fxfzaqbz.zcpt.sys.service.SysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author y1fan
 * @create 2023-01-11 15:42
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class SysDataVersionService {


    @Value("${image.localDir}")
    private String localDir;

    @Autowired
    SysAreaService sysAreaService;

    @Autowired
    private SysDataVersionRepository sysDataVersionRepository; // 数据版本管理

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    AttachmentInfoService attachmentInfoService;

    @Resource
    SUserService sUserService;
    /**
     * 保存新版本
     *
     * @param sysDataVersion
     */
    public String saveNewVersion(SysDataVersion sysDataVersion) {

        String userJson = sUserService.getSUser(sysDataVersion.getUploadUser());
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);

        sysDataVersion.setVersionCode(getVersionCode(sysDataVersion));
        sysDataVersion.setId(IdUtil.simpleUUID());
        sysDataVersion.setDelFlag(YNEnum.N.toString());
        sysDataVersion.setUploadTime(new Date());
        sysDataVersion.setUploadUser(sUser.getUserName());
        sysDataVersion.setCreateTime(new Date());
        sysDataVersion.setCreateUser(sysDataVersion.getUploadUser());
        String dataTypeLevel1Code = sysDataVersion.getDataTypeLevel1Code();
        sysDataVersion.setIsSpatialData(1);
        sysDataVersionRepository.save(sysDataVersion);
        if (dataTypeLevel1Code.equals("1")){
            gasholderService.updateByLsVersion(sysDataVersion.getTempVersionCode(),sysDataVersion.getVersionCode(),sysDataVersion.getDataRangeCountry());
        }
        if (dataTypeLevel1Code.equals("2")){
            siteService.updateByLsVersion(sysDataVersion.getTempVersionCode(),sysDataVersion.getVersionCode(),sysDataVersion.getDataRangeCountry());
        }
         return sysDataVersion.getVersionCode();
    }

    private String getVersionCode(SysDataVersion sysDataVersion) {
        return this.getVersionCode(sysDataVersion.getDataRangeCountry(),sysDataVersion.getDataTypeLevel1Code());
    }

    public synchronized String getVersionCode(@NotNull Integer sjfw,String code) {
        String dataVersionCodeSerialNumber = stringRedisTemplate.opsForValue().get(RedisKeyConstants.DATA_VERSION_CODE_SERIAL_NUMBER_KEY);
        if (StringUtils.isBlank(dataVersionCodeSerialNumber)) {
            dataVersionCodeSerialNumber = "001";
        } else {
            StringBuilder stringBuilder = new StringBuilder();
            String t = String.valueOf(Integer.parseInt(dataVersionCodeSerialNumber) + 1);
            for (int i = t.length(); i < 3; i++) {
                stringBuilder.append("0");
            }
            dataVersionCodeSerialNumber = stringBuilder.append(t).toString();
        }
        stringRedisTemplate.opsForValue().set(RedisKeyConstants.DATA_VERSION_CODE_SERIAL_NUMBER_KEY, dataVersionCodeSerialNumber);
        stringRedisTemplate.expireAt(RedisKeyConstants.DATA_VERSION_CODE_SERIAL_NUMBER_KEY, Date.from(LocalDateTime.of(LocalDate.now(), LocalTime.MAX).toInstant(ZoneOffset.of("+8"))));
       if (code.equals("1")){
           return "YW0"+sjfw+"CHQG"+DateUtil.format(new Date(), "yyyyMMdd") + dataVersionCodeSerialNumber;
       }else {
           return "YW0"+sjfw+"ZDCS"+DateUtil.format(new Date(), "yyyyMMdd") + dataVersionCodeSerialNumber;

       }

       }


    /**
     * 构建数据范围文字显示
     *
     * @param sysDataVersion 查询接口查询参数，数据版本原实体
     */
    private String buildDataRange(SysDataVersion sysDataVersion) {
        StringBuilder stringBuilder = new StringBuilder();
        String prefix = sysDataVersion.getDataRangeCountry() == 1 ? "国家级" : "省级";
        if (StringUtils.isNotBlank(sysDataVersion.getDataRangeProvince())) {
            String provinceName = sysAreaService.getAreaNameByAreaIdFromCache(sysDataVersion.getDataRangeProvince()); // 省
            if (StringUtils.isNotBlank(sysDataVersion.getDataRangeCity())) {
                String cityName = sysAreaService.getAreaNameByAreaIdFromCache(sysDataVersion.getDataRangeCity()); // 市
                if (StringUtils.isNotBlank(sysDataVersion.getDataRangeArea())) {
                    String areaName = sysAreaService.getAreaNameByAreaIdFromCache(sysDataVersion.getDataRangeArea()); // 区县
                    stringBuilder.append(prefix).append("（").append(provinceName).append(cityName).append(areaName).append("）");
                } else {
                    stringBuilder.append(prefix).append("（").append(provinceName).append(cityName).append("）");
                }
            } else {
                stringBuilder.append(prefix).append("（").append(provinceName).append("）");
            }
        } else {
            stringBuilder.append(prefix);
        }
        return stringBuilder.toString();
    }

    public void saveMetaDataInfo(SysDataVersionSaveMetaDataInfoParam param) {
        param.setUpdateTime(new Date());
        param.setUpdateUser(PlatformSessionContext.getUserID());
        sysDataVersionRepository.saveMetaDataInfo(param);
    }


    public SysDataVersionGetByVersionCodeVo getMetaDataByVersionCode(String versionCode,String typeCode) {
        SysDataVersion sysDataVersion = sysDataVersionRepository.getByVersionCode(versionCode);
        String userID = PlatformSessionContext.getUserID();
        String json = sUserService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(json, SUser.class);
        Integer fileNum=null;
        Integer fieldEntry=null;
        if (typeCode.equals("1")){
          List<Site> list=siteService.getSiteNumByVersion(versionCode);
          if (PlatformObjectUtils.isNotEmpty(list)){
              fileNum=list.get(0).getZdNum();
              fieldEntry=list.size();
          }
        }
        if (typeCode.equals("2")){
            List<Gasholder> list=gasholderService.getGasholderNumByVersion(versionCode);
            if (PlatformObjectUtils.isNotEmpty(list)){
                fileNum=list.get(0).getZdNum();
                fieldEntry=list.size();
            }
        }
        SysDataVersionGetByVersionCodeVo build = SysDataVersionGetByVersionCodeVo.builder()
                .versionCode(versionCode)
                .uploadTime(sysDataVersion.getUploadTime())
                .uploadSource(sysDataVersion.getUploadSource())
                .dataRangeCountry(sysDataVersion.getDataRangeCountry())
                .dataRangeProvince(sysDataVersion.getDataRangeProvince())
                .dataRangeCity(sysDataVersion.getDataRangeCity())
                .dataRangeArea(sysDataVersion.getDataRangeArea())
                .isSpatialData(sysDataVersion.getIsSpatialData())
                .spatialDataType(sysDataVersion.getSpatialDataType())
                .projectionInfo(sysDataVersion.getProjectionInfo())
                .fieldNum(fileNum)
                .fieldEntry(fieldEntry)
                .coordinateSystemType("大地坐标系")
                .coordinateSystemName("2000国家大地坐标系")
                .coordinateSystemEnName("CGCS2000")
                .uploadUser(sysDataVersion.getUploadUser())
                .build();

        if (sUser != null) {
            build.setUploadUser(sUser.getUserName());
        }
        return build;

    }

    /**
     * 获取用户信息
     * <p>
     * 用户id
     * 先走缓存，缓存没有调接口，然后存储缓存，配置缓存60分钟过期
     */
    public SUser getUser(String userId) {
        String redisKey = RedisKeyConstants.SYS_USER_INFO_KEY + ":" + userId;
        String userCache = stringRedisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isNotBlank(userCache)) {
            return CreateGson.createGson().fromJson(userCache, SUser.class);
        } else {
            String userJson = sUserService.getSUser(userId);
            if (StringUtils.isBlank(userJson)) {
                throw new NullPointerException();
            }
            stringRedisTemplate.opsForValue().set(redisKey, userJson);
            stringRedisTemplate.expire(redisKey, 60, TimeUnit.MINUTES);
            return CreateGson.createGson().fromJson(userJson, SUser.class);
        }
    }

    public List<String> getVersionCodeListByType(String dataType) {

        return sysDataVersionRepository.getVersionCodeListByType(dataType);
    }

    public String overwriteOldVersion(SysDataVersion sysDataVersion) {
        String userJson = sUserService.getSUser(sysDataVersion.getUploadUser());
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);

        sysDataVersionRepository.realDelByVersionCode(sysDataVersion.getVersionCode());
        sysDataVersion.setDelFlag(YNEnum.N.toString());
        sysDataVersion.setId(IdUtil.simpleUUID());
        sysDataVersion.setUploadTime(PlatformDateUtils.getCurrentTimestamp());

        sysDataVersion.setUploadUser(sUser.getUserName());
        sysDataVersion.setCreateTime(new Date());
        sysDataVersion.setCreateUser(sUser.getUserName());
        sysDataVersion.setIsSpatialData(1);
        sysDataVersionRepository.save(sysDataVersion);
        String typeCode = sysDataVersion.getDataTypeLevel1Code();
        if (typeCode.equals("1")){
            gasholderService.deleteByVersion(sysDataVersion.getVersionCode());
            gasholderService.updateLs(sysDataVersion.getVersionCode(),sysDataVersion.getTempVersionCode());
        }
        if (typeCode.equals("2")){
            siteService.deleteByVersion(sysDataVersion.getVersionCode());
            siteService.updateLs(sysDataVersion.getVersionCode(),sysDataVersion.getTempVersionCode());
        }
       // sysDataVersion.setVersionCode(getVersionCode(sysDataVersion));
        return sysDataVersion.getVersionCode();
    }

    public void delByIds(List<String> ids) {
        String currUserId = PlatformSessionUtils.getUserId();
        sysDataVersionRepository.delByIds(ids, currUserId, new Date());

    }




    public PageResult<SysDataVersionPageVo> page(SysDataVersionPageParam sysDataVersionPageParam) {
        int tPNum = sysDataVersionPageParam.getPage();
        sysDataVersionPageParam.setPage(sysDataVersionPageParam.getRows() * (Math.max(sysDataVersionPageParam.getPage(), 1) - 1));
        List<SysDataVersion> list = sysDataVersionRepository.page(sysDataVersionPageParam);
        List<SysDataVersionPageVo> restList = new ArrayList<>();
        for (SysDataVersion sysDataVersion : list) {
            SysDataVersionPageVo sysDataVersionPageVo = new SysDataVersionPageVo() {{
                setId(sysDataVersion.getId());
                setVersionCode(sysDataVersion.getVersionCode());
                setVersionTime(sysDataVersion.getVersionTime());
                setVersionDesc(sysDataVersion.getVersionDesc());
                setUploadUserId(sysDataVersion.getUploadUser());
                setUploadUser(getUser(sysDataVersion.getUploadUser()).getUserName());
                setUploadTime(sysDataVersion.getUploadTime());
                setUpdateDesc(sysDataVersion.getUpdateDesc());
                setDataName(sysDataVersion.getDataName());
                setDataDesc(sysDataVersion.getDataDesc());
                setDataRange(sysDataVersion.getDataRangeStr());

            }};
            if (StringUtils.isNotBlank(sysDataVersion.getDataFileIds())) {
                String[] dataFileIds = sysDataVersion.getDataFileIds().split(",");
                List<SysDataVersionPageVo.DataFile> dataFileList = new ArrayList<>();
                for (String dataFileId : dataFileIds) {
                    AttachmentInfoEntity attach = attachmentInfoService.getAttach(dataFileId);
                    if (null != attach) {
                        SysDataVersionPageVo.DataFile dataFile = new SysDataVersionPageVo.DataFile();
                        dataFile.setId(attach.getAttachId());
                        dataFile.setName(attach.getAttachName());
                        dataFileList.add(dataFile);
                    }
                    sysDataVersionPageVo.setDataFileList(dataFileList);
                }
            }
            if (StringUtils.isNotBlank(sysDataVersion.getAttachmentIds())) {
                String[] attachIds = sysDataVersion.getAttachmentIds().split(",");
                List<SysDataVersionPageVo.Attachment> attachmentList = new ArrayList<>();
                for (String dataFileId : attachIds) {
                    AttachmentInfoEntity attach = attachmentInfoService.getAttach(dataFileId);
                    if (null != attach) {
                        SysDataVersionPageVo.Attachment attachment = new SysDataVersionPageVo.Attachment();
                        attachment.setId(attach.getAttachId());
                        attachment.setName(attach.getAttachName());
                        attachmentList.add(attachment);
                    }
                    sysDataVersionPageVo.setAttachmentList(attachmentList);
                }
            }
            restList.add(sysDataVersionPageVo);
        }
        Integer total = sysDataVersionRepository.countForPage(sysDataVersionPageParam);
        return new PageResult<>(tPNum, sysDataVersionPageParam.getRows(), PageUtil.totalPage(total, sysDataVersionPageParam.getRows()), total, restList);

    }

    public List<SysDataVersionPageVo> list(SysDataVersionPageParam sysDataVersionPageParam) {
        sysDataVersionPageParam.setRows(null);
        sysDataVersionPageParam.setPage(null);
        List<SysDataVersion> list = sysDataVersionRepository.page(sysDataVersionPageParam);
        List<SysDataVersionPageVo> restList = new ArrayList<>();
        for (SysDataVersion sysDataVersion : list) {
            SysDataVersionPageVo sysDataVersionPageVo = new SysDataVersionPageVo() {{
                setId(sysDataVersion.getId());
                setVersionCode(sysDataVersion.getVersionCode());
                setVersionTime(sysDataVersion.getVersionTime());
                setVersionDesc(sysDataVersion.getVersionDesc());
                setUploadUserId(sysDataVersion.getUploadUser());
                setUploadUser(getUser(sysDataVersion.getUploadUser()).getUserName());
                setUploadTime(sysDataVersion.getUploadTime());
                setUpdateDesc(sysDataVersion.getUpdateDesc());
                setDataName(sysDataVersion.getDataName());
                setDataDesc(sysDataVersion.getDataDesc());
              setDataRange(sysDataVersion.getDataRangeStr());
            }};
            if (StringUtils.isNotBlank(sysDataVersion.getDataFileIds())) {
                String[] dataFileIds = sysDataVersion.getDataFileIds().split(",");
                List<SysDataVersionPageVo.DataFile> dataFileList = new ArrayList<>();
                for (String dataFileId : dataFileIds) {
                    AttachmentInfoEntity attach = attachmentInfoService.getAttach(dataFileId);
                    if (attach != null) {
                        SysDataVersionPageVo.DataFile dataFile = new SysDataVersionPageVo.DataFile();
                        dataFile.setId(attach.getAttachId());
                        dataFile.setName(attach.getAttachName());
                        dataFileList.add(dataFile);
                    }
                    sysDataVersionPageVo.setDataFileList(dataFileList);
                }
            }
            if (StringUtils.isNotBlank(sysDataVersion.getAttachmentIds())) {
                String[] attachIds = sysDataVersion.getAttachmentIds().split(",");
                List<SysDataVersionPageVo.Attachment> attachmentList = new ArrayList<>();
                for (String dataFileId : attachIds) {
                    AttachmentInfoEntity attach = attachmentInfoService.getAttach(dataFileId);
                    if (attach != null) {
                        SysDataVersionPageVo.Attachment attachment = new SysDataVersionPageVo.Attachment();
                        attachment.setId(attach.getAttachId());
                        attachment.setName(attach.getAttachName());
                        attachmentList.add(attachment);
                    }
                    sysDataVersionPageVo.setAttachmentList(attachmentList);
                }
            }
            restList.add(sysDataVersionPageVo);
        }
        return restList;
    }

    public List<List<String>> parseExcel(String fileId)throws IOException {
        List<List<String>> data = getDate(fileId);
        return data;
    }

    private List<List<String>> getDate(String fileId)throws IOException {
        List<List<String>> objects = new ArrayList<>();
        //根据id和文件名获取真实的放在磁盘上的文件
        AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(fileId);
        String attachPath = attachmentInfoEntity.getAttachPath();
        //拼接真实路径
        String name = localDir + "\\" + attachPath;
        File file = new File(name);
        // TODO 测试用，写完shp文件解析后删除该if
        if (!FileUtil.getSuffix(file.getName()).equals("xlsx")) {
            return objects;
        }
        try {
            FileInputStream fis = new FileInputStream(file);
            //获取excel表格数据
            List<List<String>> lists = ExcelReaderUtil.readExcel(fis);
            fis.close();
            if (null == lists) {
                return null;
            }
            objects.addAll(lists);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return objects;
    }

    public RestResponse parseShp(String fileIds,String typeCode) throws Exception {
        this.uniformFileName(fileIds);
        ParsingResult shpData = getShpData(fileIds);
        //是否成功
        if (!shpData.getMessage().equals("ok")) {
            return RestResponse.fail(shpData.getMessage());
        }
        RestResponse restResponse =null;
        if (typeCode.equals("1")){
            try {
               restResponse = gasholderService.saveShpTemporaryData(shpData);
                return restResponse;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return RestResponse.fail("该数据类别下没有shp数据");
            }
        }
        if (typeCode.equals("2")){
            try {
                restResponse = siteService.saveShpTemporaryData(shpData);
                return restResponse;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return RestResponse.fail("该数据类别下没有shp数据");
            }
        }
        return restResponse;
    }

    /**
     * 统一文件名
     *
     * @param fileIds
     */
    public void uniformFileName(String fileIds) {
        String[] idList = fileIds.split(",");
        AttachmentInfoEntity attachRoot = attachmentInfoService.getAttach(idList[0]);
        String attachRootPath = attachRoot.getAttachPath();
        String filePathCurrTime = getFilePathCurrTime(attachRootPath);
        for (int i = 1; i < idList.length; i++) {
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(idList[i]);
            if (getFilePathCurrTime(attach.getAttachPath()).equals(filePathCurrTime)) {
                continue;
            }
            String attachPath = attach.getAttachPath();
            String fileDiskPath = localDir + attachPath;
            FileUtil.rename(new File(fileDiskPath), getNonSuffixFileName(attach.getAttachName()) + "_" + filePathCurrTime + "." + FileUtil.getSuffix(attach.getAttachName()), true);
            String[] s = attachPath.split("_");
            attach.setAttachPath(s[0] + "_" + filePathCurrTime + "." + FileUtil.getSuffix(attach.getAttachName()));
            attachmentInfoService.update(attach);
        }
    }

    private String getNonSuffixFileName(String fileName) {
        return fileName.replaceAll("." + FileUtil.getSuffix(fileName), "");
    }

    private String getFilePathCurrTime(String filePath) {
        return filePath.split("_")[1].replaceAll("." + FileUtil.getSuffix(filePath.split("_")[1]), "");
    }




    public ParsingResult getShpData(String fileIds) throws Exception {
        //.prj结尾用来校验是否为2000坐标系
        String prj = "";
        //.cpg文件用来获得编码格式,例如utf-8
        String cpg = "";
        //.shp文件用来获得数据
        String shp = "";
        //根据id获取真实地址
        String[] split = fileIds.split(",");
        for (String id : split) {
            //根据id和文件名获取真实的放在磁盘上的文件
            AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(id);
            String attachPath = attachmentInfoEntity.getAttachPath();
            String substring = attachPath.substring(attachPath.length() - 4);
            if (substring.equals(".prj")) {
                prj = localDir + File.separator + attachPath;
            } else if (substring.equals(".cpg")) {
                cpg = localDir + File.separator + attachPath;
            } else if (substring.equals(".shp")) {
                shp = localDir + File.separator + attachPath;
            }
        }
        return ShpAnalyticUtil.analytic(prj, cpg, shp);
    }

    public void dataExport(HttpServletResponse response, List<String> idList, boolean b)throws IOException {
        List<SysDataVersion> list = sysDataVersionRepository.selectByIds(idList);
        List<SysDataVersionExportModel> exportModels = new ArrayList<>();
        for (SysDataVersion sysDataVersion : list) {
            SysDataVersionExportModel sysDataVersionExportModel = new SysDataVersionExportModel();
            sysDataVersionExportModel.setVersionTime(DateUtil.format(sysDataVersion.getVersionTime(), "yyyy-MM-dd"));
            sysDataVersionExportModel.setVersionCode(sysDataVersion.getVersionCode());
            sysDataVersionExportModel.setDataName(sysDataVersion.getDataName());
            sysDataVersionExportModel.setDataType("1");
            sysDataVersionExportModel.setDataRange(sysDataVersion.getDataRangeStr());
            sysDataVersionExportModel.setUploadTime(DateUtil.format(sysDataVersion.getUpdateTime(), "yyyy-MM-dd"));
            sysDataVersionExportModel.setUploadUser(getUser(sysDataVersion.getUploadUser()).getUserName());
            sysDataVersionExportModel.setVersionDesc(sysDataVersion.getVersionDesc());
            sysDataVersionExportModel.setDataDesc(sysDataVersion.getDataDesc());
            sysDataVersionExportModel.setUpdateDesc(sysDataVersion.getUpdateDesc());
            exportModels.add(sysDataVersionExportModel);
        }
        List<ExcelUtil.ExcelAlias> aliasList = new ArrayList<>();
        aliasList.add(new ExcelUtil.ExcelAlias("versionTime", "版本时间"));
        aliasList.add(new ExcelUtil.ExcelAlias("versionCode", "版本号"));
        aliasList.add(new ExcelUtil.ExcelAlias("dataName", "数据名称"));
        aliasList.add(new ExcelUtil.ExcelAlias("dataType", "数据类别"));
        aliasList.add(new ExcelUtil.ExcelAlias("dataRange", "数据范围"));
        aliasList.add(new ExcelUtil.ExcelAlias("uploadTime", "上传时间"));
        aliasList.add(new ExcelUtil.ExcelAlias("uploadUser", "上传人"));
        aliasList.add(new ExcelUtil.ExcelAlias("versionDesc", "版本说明"));
        aliasList.add(new ExcelUtil.ExcelAlias("dataDesc", "数据说明"));
        aliasList.add(new ExcelUtil.ExcelAlias("updateDesc", "更新说明"));
        if (b) {
            this.exportDataVersion2Zip(exportModels, aliasList, list, response);
        } else {
            ExcelUtil.exportExcel(exportModels, aliasList, "data_version_" + System.currentTimeMillis(), response);
        }
    }

    private void exportDataVersion2Zip
            (List<SysDataVersionExportModel> exportModels, List<ExcelUtil.ExcelAlias> alias, Iterable<? extends
                    SysDataVersion> list, HttpServletResponse response) throws FileNotFoundException {
        List<ZipUtils.ZipExportWeb> fileList = new ArrayList<>();
        File excelFile = ExcelUtil.createExcel(exportModels, alias, ResourceUtils.getURL("classpath:").getPath() + File.separator + "cache_file" + File.separator + System.currentTimeMillis() + ".xlsx");
        fileList.add(new ZipUtils.ZipExportWeb(excelFile, null));
        for (SysDataVersion sysDataVersion : list) {
            String attachmentIds = sysDataVersion.getAttachmentIds();
            if (StringUtils.isNotBlank(attachmentIds)) {
                String[] idArr = attachmentIds.split(",");
                for (String id : idArr) {
                    String attachPath = attachmentInfoService.getAttach(id).getAttachPath();
                    fileList.add(new ZipUtils.ZipExportWeb(new File(localDir + attachPath), sysDataVersion.getVersionCode()));
                }
            }
            String dataFileIds = sysDataVersion.getDataFileIds();
            if (StringUtils.isNotBlank(dataFileIds)) {
                String[] idArr = dataFileIds.split(",");
                for (String id : idArr) {
                    String attachPath = attachmentInfoService.getAttach(id).getAttachPath();
                    fileList.add(new ZipUtils.ZipExportWeb(new File(localDir + attachPath), sysDataVersion.getVersionCode()));
                }
            }
        }
        ZipUtils.exportZip(fileList, "data_version_" + System.currentTimeMillis(), response);
        FileUtil.del(excelFile);
    }

    @Resource
    GasholderService gasholderService;
    @Resource
    SiteService siteService;

    public List<Gasholder> getDataView(SysDataVersionPageParam sysDataVersionPageParam) {
        List<Gasholder> gasholders = gasholderService.getDataByTypeAndVersion(sysDataVersionPageParam);
        if (gasholders.size()>0||gasholders!=null){
            for (Gasholder gasholder : gasholders) {
                String dataVersion = gasholder.getDataVersion();

                SysDataVersion byVersionCode = sysDataVersionRepository.getByVersionCode(dataVersion);
                if (byVersionCode!=null){
                    gasholder.setVersionDesc(byVersionCode.getVersionDesc());
                    gasholder.setDataDesc(byVersionCode.getDataDesc());
                }

            }
            return gasholders;
        }else {
            return null;
        }


    }

    public List<Site> getSiteDataView(SysDataVersionPageParam sysDataVersionPageParam) {
        List<Site> siteDataView = siteService.getSiteDataView(sysDataVersionPageParam);
        if (siteDataView.size()>0||siteDataView!=null){
            for (Site site : siteDataView) {
                String dataVersion = site.getDataVersion();
                SysDataVersion byVersionCode = sysDataVersionRepository.getByVersionCode(dataVersion);
                if (byVersionCode!=null){
                    site.setVersionDesc(byVersionCode.getVersionDesc());
                    site.setDataDesc(byVersionCode.getDataDesc());
                }
            }
            return siteDataView;
        }else {
            return null;
        }




    }

    public Map<String, Object> sameTypeDataExist(SysDataVersionSameTypeDataExistParam sysDataVersionSameTypeDataExistParam) {
        String versionCode = sysDataVersionRepository.sameTypeDataExist(sysDataVersionSameTypeDataExistParam);
        boolean isExist = StringUtils.isNotBlank(versionCode);
        return new HashMap<String, Object>() {
            {
                put("isExist", isExist);
                if (isExist) {
                    if (sysDataVersionSameTypeDataExistParam.getDataTypeLevel1().equals("1")){
                        put("tipMsg", "本系统已有同类储气罐数据（版本号为" + versionCode + "），是否作为新版本数据进行上传？");
                        put("versionCode", versionCode);
                    }
                    if (sysDataVersionSameTypeDataExistParam.getDataTypeLevel1().equals("2")){
                        put("tipMsg", "本系统已有同类重点场所数据（版本号为" + versionCode + "），是否作为新版本数据进行上传？");
                        put("versionCode", versionCode);
                    }

                }
            }
        };
    }

    public List<SysDataVersion> getDataVersionView(SysDataVersionPageParam sysDataVersionPageParam) {
        return sysDataVersionRepository.getDataVersionView(sysDataVersionPageParam);
    }

    public Map<String,Object> getFyDataView(VersionVO versionVO) {
        return sysDataVersionRepository.getFyDataView(versionVO);
    }


    public static class SysDataVersionExportModel {
        private String versionTime;
        private String versionCode;
        private String dataName;
        private String dataType;
        private String dataRange;
        private String uploadTime;
        private String uploadUser;
        private String versionDesc;
        private String dataDesc;
        private String updateDesc;

        public String getVersionTime() {
            return versionTime;
        }

        public void setVersionTime(String versionTime) {
            this.versionTime = versionTime;
        }

        public String getVersionCode() {
            return versionCode;
        }

        public void setVersionCode(String versionCode) {
            this.versionCode = versionCode;
        }

        public String getDataName() {
            return dataName;
        }

        public void setDataName(String dataName) {
            this.dataName = dataName;
        }

        public String getDataType() {
            return dataType;
        }

        public void setDataType(String dataType) {
            this.dataType = dataType;
        }

        public String getDataRange() {
            return dataRange;
        }

        public void setDataRange(String dataRange) {
            this.dataRange = dataRange;
        }

        public String getUploadTime() {
            return uploadTime;
        }

        public void setUploadTime(String uploadTime) {
            this.uploadTime = uploadTime;
        }

        public String getUploadUser() {
            return uploadUser;
        }

        public void setUploadUser(String uploadUser) {
            this.uploadUser = uploadUser;
        }

        public String getVersionDesc() {
            return versionDesc;
        }

        public void setVersionDesc(String versionDesc) {
            this.versionDesc = versionDesc;
        }

        public String getDataDesc() {
            return dataDesc;
        }

        public void setDataDesc(String dataDesc) {
            this.dataDesc = dataDesc;
        }

        public String getUpdateDesc() {
            return updateDesc;
        }

        public void setUpdateDesc(String updateDesc) {
            this.updateDesc = updateDesc;
        }
    }
}
